package com.zhongshengnetwork.rightbe.wzt.activity;

import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

import android.Manifest;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.alibaba.fastjson.JSONObject;
import com.tencent.connect.share.QQShare;
import com.tencent.mm.opensdk.modelmsg.SendMessageToWX;
import com.tencent.mm.opensdk.modelmsg.WXImageObject;
import com.tencent.mm.opensdk.modelmsg.WXMediaMessage;
import com.tencent.tauth.IUiListener;
import com.tencent.tauth.UiError;
import com.zhongshengnetwork.rightbe.Constant.APIKey;
import com.zhongshengnetwork.rightbe.Constant.Constant;
import com.zhongshengnetwork.rightbe.CustomApplication;
import com.zhongshengnetwork.rightbe.MainActivity;
import com.zhongshengnetwork.rightbe.R;
import com.zhongshengnetwork.rightbe.common.BroadcastDefine;
import com.zhongshengnetwork.rightbe.common.CommonUtils;
import com.zhongshengnetwork.rightbe.common.Des;
import com.zhongshengnetwork.rightbe.common.GsonTools;
import com.zhongshengnetwork.rightbe.common.PermissionUtils;
import com.zhongshengnetwork.rightbe.common.ScreenUtils;
import com.zhongshengnetwork.rightbe.common.TopBarView;
import com.zhongshengnetwork.rightbe.common.activity.AppBaseActivity;
import com.zhongshengnetwork.rightbe.common.callback.PermissionCallback;
import com.zhongshengnetwork.rightbe.common.customview.ActionSheetDialog;
import com.zhongshengnetwork.rightbe.common.customview.CustomDialog;
import com.zhongshengnetwork.rightbe.common.customview.ShareDialog;
import com.zhongshengnetwork.rightbe.common.utils.ToastUtil;
import com.zhongshengnetwork.rightbe.gsonmodel.ClassifyModel;
import com.zhongshengnetwork.rightbe.gsonmodel.CommonModel;
import com.zhongshengnetwork.rightbe.https.HttpCallBack;
import com.zhongshengnetwork.rightbe.https.HttpsUtils;
import com.zhongshengnetwork.rightbe.login.LoginActivity;
import com.zhongshengnetwork.rightbe.qrcode.tools.QRCodeUtil;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import static com.zhongshengnetwork.rightbe.MainActivity.REQ_PERM_EXTERNAL_STORAGE;

public class ClassifyShareCodeActivity extends AppBaseActivity implements TopBarView.onTitleBarClickListener {

    private TopBarView topbar;
    private ImageView qrcodeImageView;
    private TextView qrcode_title;
    private RelativeLayout qrcode_img_layout;
    private ClassifyModel classifyModel;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_classify_share_code);
        classifyModel = (ClassifyModel)getIntent().getSerializableExtra("model");

        qrcode_title = (TextView) findViewById(R.id.qrcode_title);
        qrcode_title.setText(classifyModel.getClassifyName());
        qrcode_img_layout = (RelativeLayout) findViewById(R.id.qrcode_img_layout);
        topbar = (TopBarView)findViewById(R.id.topbar);
        topbar.setClickListener(this);
        topbar.getRightView().setImageResource(R.drawable.more);
        topbar.getRightView().setClickable(true);
        topbar.getRightView().setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                if (CommonUtils.isLogin() == false){
                    Intent intent = new Intent(ClassifyShareCodeActivity.this, LoginActivity.class);
                    startActivity(intent);
                    return;
                }

                PermissionUtils.isPictureNote(ClassifyShareCodeActivity.this, new PermissionCallback() {
                    @Override
                    public void onResult(boolean flag, boolean showAlert) {
                        if (flag == true){
                            final List<String> menu = new ArrayList<String>();
                            menu.add("保存");
                            if (classifyModel.isNeedAuth() == true){
                                menu.add("重置二维码");
                            }
                            //menu.add("分享");
                            ActionSheetDialog actionSheetDialog = new ActionSheetDialog(ClassifyShareCodeActivity.this)
                                    .builder()
                                    .setTitle("")
                                    .setCancelable(false)
                                    .setCanceledOnTouchOutside(true);
                            for (String m : menu){
                                actionSheetDialog.addSheetItem(m, null, new ActionSheetDialog.OnSheetItemClickListener() {
                                    @Override
                                    public void onClick(int which) {
                                        if (which == 1){
                                            final Bitmap bitmap = viewConversionBitmap(qrcode_img_layout);
                                            if (bitmap != null){
                                                CommonUtils.saveBmp2Gallery(bitmap,System.currentTimeMillis()+"");
                                            }
                                        }else if (which == 2){
                                            resetCode();
                                        }
                                    }
                                });
                            }
                            actionSheetDialog.show();
                        }
                    }
                });

            }
        });

        qrcodeImageView = (ImageView) findViewById(R.id.activity_qrcode_qrimg);
        final String filePath = getFileRoot(ClassifyShareCodeActivity.this) + File.separator
                + "qr_" + System.currentTimeMillis() + ".jpg";

        //二维码图片较大时，生成图片、保存文件的时间可能较长，因此放在新线程中
        new Thread(new Runnable() {
            @Override
            public void run() {
                String content = Constant.QRCodeHOST+"classify/share.do?";
                try {
                    String code = classifyModel.getClassifyId()+"";
                    if (classifyModel.isNeedAuth() == true && !CommonUtils.isEmpty(classifyModel.getAuthCode())){
                        code = classifyModel.getAuthCode();
                    }
                    code = Des.encryptDES(code,Constant.DESKey);
                    content += code;
                }catch (Exception e){
                    return;
                }
                int W = dip2px(ClassifyShareCodeActivity.this, ScreenUtils.getScreenWidth(ClassifyShareCodeActivity.this));
                boolean success = QRCodeUtil.createQRImage(content, W, W,
                        null,
                        filePath);

                if (success) {
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            qrcodeImageView.setImageBitmap(BitmapFactory.decodeFile(filePath));
                        }
                    });
                }
            }
        }).start();

    }

    private static Bitmap viewConversionBitmap(View v) {
        int w = v.getWidth();
        int h = v.getHeight();
        Log.e("TAG", "width: " + w + " height: " + h);
        Bitmap bmp = Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_8888);
        Canvas c = new Canvas(bmp);

        c.drawColor(Color.WHITE);
        /** 如果不设置canvas画布为白色，则生成透明 */

        //v.layout(0, 0, w, h);
        v.draw(c);

        return bmp;
    }


    //文件存储根目录
    private String getFileRoot(Context context) {
        if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
            File external = context.getExternalFilesDir(null);
            if (external != null) {
                return external.getAbsolutePath();
            }
        }
        return context.getFilesDir().getAbsolutePath();
    }

    public static int dip2px(Context context, float dpValue) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (dpValue * scale + 0.5f);
    }

    public static int px2dip(Context context, float pxValue) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (pxValue / scale + 0.5f);
    }

    /**
     * 点击了返回导航按钮
     */
    @Override
    public void onBackClick() {
        //Toast.makeText(LoginActivity.this, "你点击了左侧按钮", Toast.LENGTH_LONG).show();
        finish();
    }

    /**
     * 点击了右边导航按钮
     */
    @Override
    public void onRightClick() {

    }

    private void resetCode(){
        CustomDialog dialog = null;
        final CustomDialog.Builder builder = new CustomDialog.Builder(ClassifyShareCodeActivity.this);
        builder.setTitle("温馨提示");
        builder.setMessage("重置后，原来的二维码将会失效，确定要重置吗？");
        builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
                final HashMap<String, String> map = new HashMap<String, String>();
                String url = "weishu/classify/edit.do";
                map.put("token", CommonUtils.formatString(CustomApplication.loginModel.getToken()));
                map.put("icon",classifyModel.getIcon());
                map.put("title",classifyModel.getClassifyName());
                map.put("visible",classifyModel.getVisible()+"");
                map.put("needAuth",classifyModel.isNeedAuth()+"");
                map.put("changeAuthCode","true");
                map.put("classifyId",classifyModel.getClassifyId()+"");
                HttpsUtils.miniAppDo(map, url, new HttpCallBack() {
                    @Override
                    public void onSuccess(String data) {
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                CommonModel commonModel = GsonTools.getCommonModel(data);
                                if (commonModel.getFlag().equals("1")){

                                    classifyModel.setAuthCode(GsonTools.getClassifyAuthCode(data));

                                   ToastUtil.show(ClassifyShareCodeActivity.this, "重置成功");
                                    final String filePath = getFileRoot(ClassifyShareCodeActivity.this) + File.separator
                                            + "qr_" + System.currentTimeMillis() + ".jpg";

                                    //二维码图片较大时，生成图片、保存文件的时间可能较长，因此放在新线程中
                                    new Thread(new Runnable() {
                                        @Override
                                        public void run() {
                                            String content = Constant.QRCodeHOST+"classify/share.do?";
                                            try {
                                                String code = classifyModel.getClassifyId()+"";
                                                if (classifyModel.isNeedAuth() == true && !CommonUtils.isEmpty(classifyModel.getAuthCode())){
                                                    code = classifyModel.getAuthCode();
                                                }
                                                code = Des.encryptDES(code,Constant.DESKey);
                                                content += code;
                                            }catch (Exception e){
                                                return;
                                            }
                                            int W = dip2px(ClassifyShareCodeActivity.this, ScreenUtils.getScreenWidth(ClassifyShareCodeActivity.this));
                                            boolean success = QRCodeUtil.createQRImage(content, W, W,
                                                    null,
                                                    filePath);

                                            if (success) {
                                                runOnUiThread(new Runnable() {
                                                    @Override
                                                    public void run() {
                                                        qrcodeImageView.setImageBitmap(BitmapFactory.decodeFile(filePath));
                                                    }
                                                });
                                            }
                                        }
                                    }).start();
                                }else {
                                    ToastUtil.show(ClassifyShareCodeActivity.this, commonModel.getMsg());
                                }
                            }
                        });
                    }

                    @Override
                    public void onError(String msg) {
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                ToastUtil.show(ClassifyShareCodeActivity.this, "重置失败");
                            }
                        });
                    }
                });
            }
        });
        builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
            }
        });
        dialog = builder.create();
        dialog.show();
    }

    private void showShare(){
        final ShareDialog shareDialog = new ShareDialog(ClassifyShareCodeActivity.this)
                .builder()
                .setCancelable(false)
                .setCanceledOnTouchOutside(true);
        shareDialog.friend_share.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                shareDialog.dialog.dismiss();
                //分享到朋友圈
                shareToWX(0, classifyModel.getClassifyName());

            }
        });
        shareDialog.wx_share.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                shareDialog.dialog.dismiss();
                //分享给微信好友
                shareToWX(1, classifyModel.getClassifyName());

            }
        });
        shareDialog.wb_share.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                shareDialog.dialog.dismiss();
                String shareUrl = Constant.QRCodeHOST+"classify/share.do?";
                try {
                    String code = classifyModel.getClassifyId()+"";
                    if (classifyModel.isNeedAuth() == true && !CommonUtils.isEmpty(classifyModel.getAuthCode())){
                        code = classifyModel.getAuthCode();
                    }
                    code = Des.encryptDES(code,Constant.DESKey);
                    shareUrl += code;
                }catch (Exception e){
                    return;
                }
                //微博
                CustomApplication.WbShareType = 4;
                CustomApplication.WbShareSourceId = classifyModel.getClassifyId()+"";
                CustomApplication.WbShareTitle = classifyModel.getClassifyName();
                CustomApplication.WbShareText = classifyModel.getClassifyName();
                CustomApplication.WbShareActionUrl = shareUrl;
                Intent mIntent = new Intent(BroadcastDefine.WeiBo_Share_Action);
                //发送广播
                sendBroadcast(mIntent);
            }
        });
        shareDialog.qq_share.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                shareDialog.dialog.dismiss();
                //分享到qq
                shareToQQ(0, classifyModel.getClassifyName());

            }
        });
        shareDialog.zone_share.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                shareDialog.dialog.dismiss();
                //qq空间
                shareToQQ(1, classifyModel.getClassifyName());

            }
        });
        shareDialog.show();
    }

    private String buildTransaction(final String type) {
        return (type == null) ? String.valueOf(System.currentTimeMillis()) : type + System.currentTimeMillis();
    }
    //分享文字到微信
    private void shareToWX(int type, String title){

        final Bitmap bitmap = viewConversionBitmap(qrcode_img_layout);
        if (bitmap == null){
            return;
        }
        WXImageObject imgObj = new WXImageObject(bitmap);
        WXMediaMessage msg = new WXMediaMessage();
        msg.mediaObject = imgObj;
        msg.description = title;
        //设置缩略图
        Bitmap thumbBmp = Bitmap.createScaledBitmap(bitmap, 200, 200, true);
        bitmap.recycle();
        msg.thumbData = CommonUtils.bitmapToBytes(thumbBmp);//Util.bmpToByteArray(thumbBmp, true);

        SendMessageToWX.Req req = new SendMessageToWX.Req();
        req.transaction = buildTransaction("img");
        req.message = msg;
        req.scene = type==0 ? SendMessageToWX.Req.WXSceneTimeline:SendMessageToWX.Req.WXSceneSession;
        CustomApplication.mWxApi.sendReq(req);

    }

    private MyIUiListener mIUiListener = new MyIUiListener();
    class MyIUiListener implements IUiListener {
        @Override
        public void onComplete(Object o) {
            //Log.e("TAG","分享成功");
        }

        @Override
        public void onError(UiError uiError) {
            Log.e("TAG","分享出错");
        }

        @Override
        public void onCancel() {
            Log.e("TAG","分享取消");
        }

        @Override
        public void onWarning(int i) {

        }
    }

    //分享到qq
    private Bundle params;
    private void shareToQQ(int type,String title){
        final Bitmap bitmap = viewConversionBitmap(qrcode_img_layout);
        if (bitmap == null){
            return;
        }
        String shareUrl = Constant.QRCodeHOST+"classify/share.do?";
        try {
            String code = classifyModel.getClassifyId()+"";
            if (classifyModel.isNeedAuth() == true && !CommonUtils.isEmpty(classifyModel.getAuthCode())){
                code = classifyModel.getAuthCode();
            }
            code = Des.encryptDES(code,Constant.DESKey);
            shareUrl += code;
        }catch (Exception e){
            return;
        }
        String localPath = CommonUtils.getSaveBmp2Gallery(bitmap, System.currentTimeMillis()+"");
        params = new Bundle();
        if (type == 0){//分享给QQ好友

            if (!CommonUtils.isEmpty(localPath)){
                params.putInt(QQShare.SHARE_TO_QQ_KEY_TYPE, QQShare.SHARE_TO_QQ_TYPE_DEFAULT);
                params.putString(QQShare.SHARE_TO_QQ_TITLE, title);// 标题
                params.putString(QQShare.SHARE_TO_QQ_SUMMARY, title);// 摘要
                params.putString(QQShare.SHARE_TO_QQ_TARGET_URL,shareUrl);// 内容地址LangShareUrl+langInfoModel.getLangid()
                params.putString(QQShare.SHARE_TO_QQ_IMAGE_LOCAL_URL, localPath);
                params.putString(QQShare.SHARE_TO_QQ_EXT_INT, "");//其它附加功能
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        CustomApplication.mTencent.shareToQQ(ClassifyShareCodeActivity.this, params, mIUiListener);
                        CommonUtils.deleteFileByPath(localPath);
                    }
                });
            }

        }else if(type == 1){
            //分享到QQ空间
            if (!CommonUtils.isEmpty(localPath)){
                params.putInt(QQShare.SHARE_TO_QQ_KEY_TYPE, QQShare.SHARE_TO_QQ_TYPE_DEFAULT);
                params.putString(QQShare.SHARE_TO_QQ_TITLE, title);// 标题
                params.putString(QQShare.SHARE_TO_QQ_SUMMARY, title);// 摘要
                params.putString(QQShare.SHARE_TO_QQ_TARGET_URL,shareUrl);// 内容地址LangShareUrl+langInfoModel.getLangid()
                params.putString(QQShare.SHARE_TO_QQ_IMAGE_LOCAL_URL, localPath);
                params.putString(QQShare.SHARE_TO_QQ_EXT_INT, "");//其它附加功能
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        CustomApplication.mTencent.shareToQzone(ClassifyShareCodeActivity.this, params, mIUiListener);
                        CommonUtils.deleteFileByPath(localPath);
                    }
                });
            }
        }
    }

}
